<template>
  <basic-container>
    <el-tabs v-model="selectTab" class="demo-tabs" @tab-click="handleChange">
      <el-tab-pane
        :label="item.label"
        :name="item.prop"
        v-for="item in tabOption.column"
        :key="item.prop"
      ></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
<!--      <template #menu-left>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.followUpVisitPlan_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button>
      </template>-->
      <template #menu="{ row, index }">
        <el-button text type="primary" v-if="selectTab === 3" @click="handleMenu(0, row, index)"
          >重命名
        </el-button>
        <el-button text type="primary" v-if="selectTab === 3" @click="handleMenu(1, row, index)"
          >编 辑
        </el-button>
        <el-button
          text
          type="primary"
          v-if="selectTab === 3 && row.publicShare != '1'"
          @click="handleMenu(2, row, index)"
          >公开共享
        </el-button>
        <el-button
          text
          type="primary"
          v-if="selectTab === 3 && row.publicShare != '1' && row.deptShare != '1'"
          @click="handleMenu(3, row, index)"
          >机构共享
        </el-button>
        <el-button
          text
          type="primary"
          v-if="selectTab === 3"
          @click="handleMenu(4, row, index)"
          style="color: red"
          >删 除
        </el-button>
        <el-button text type="primary" v-if="selectTab != 3" @click="handleMenu(5, row, index)"
          >复 制
        </el-button>
      </template>
      <template #isShareSelect="{ row }">
        <span
          :style="{
            color:
              row.isShareSelect === 1 ? '#0077bd' : row.isShareSelect === 2 ? '#398439' : '#fb9a00',
          }"
          style="font-weight: 550"
          >{{ ['公开共享', '机构共享', '私有'][row.isShareSelect - 1] }}</span
        >
      </template>
      <template #name="{ row, index }">
        <div
          style="display: flex; align-items: center; justify-content: center"
          :style="!routerQuery.isCase ? 'cursor: pointer;color: #3c8dbc' : ''"
          @click="handleMenu(6, row, index)"
        >
          <span>{{ row.name }}</span>
          <!-- <Lock style="width: 14px; height: 14px; margin-left: 5px" v-if="row.status == 2 && !routerQuery.isCase" /> -->
        </div>
      </template>
    </avue-crud>
    <visitPlanItem ref="visitplanitemRef" />
  </basic-container>
</template>

<script setup>
import visitPlanItem from './components/visitPlanItem.vue';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  toShare,
  copy,
} from '@/api/followupvisitplan/followUpVisitPlan';
import option from '@/option/followupvisitplan/followUpVisitPlan';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import website from '@/config/website';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const crud = ref(null);
const store = useStore();
const backRoutesVal = computed(() => store.getters.backRoutesVal);
const tabOption = reactive({
  column: [
    {
      // icon: 'el-icon-info',
      label: '公开共享',
      prop: 1,
    },
    {
      label: '机构共享',
      prop: 2,
    },
    {
      label: '私有计划',
      prop: 3,
    },
  ],
});
const selectTab = ref(1);
const routerQuery = ref({});
// routerQuery.value = route.query;
const options = ref(option);
const form = ref({});
const query = ref({
  shareType: 1,
});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const data = ref([]);
let visitplanitemRef = ref(null,null);
// 获取 Vuex 中的 permission getter
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);

// permissionList 计算属性
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  addBtn: validData(permission.value.followUpVisitPlan_add, false),
  viewBtn: validData(permission.value.followUpVisitPlan_view, false),
  delBtn: validData(permission.value.followUpVisitPlan_delete, false),
  editBtn: validData(permission.value.followUpVisitPlan_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
const handleChange = tab => {
  selectTab.value = tab.props.name;
  // TabRefreshChange();
  store.commit('SET_TAB', selectTab.value);
  for (const key in search.value) {
    search.value[key] = '';
  }
  searchReset();
  options.value.menuWidth = selectTab.value === 3 ? 420 : 200;
};

// 操作栏按钮点击事件
/*
  type: 0 重命名
  type: 1 编辑
  type: 2 公开共享
  type: 3 机构共享
  type: 4 删除
  type: 5 复 制
  type: 6 查看
*/
const handleMenu = (type, row = {}, index = null) => {
  console.log(1111,type)
  const actions = {
    0: () => {
      crud.value.rowEdit(row, index);
    },
    1: () => {
      visitplanitemRef.value.open(row,true);
    },
    2: () => postToShare(row, '1'),
    3: () => postToShare(row, '2'),
    4: () => {
      crud.value.rowDel(row, index);
    },
    5: () => postCopy(row),
    6: () => {
      visitplanitemRef.value.open(row,false);
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};

const postToShare = (row, shareType) => {
  postAction(
    `确定将该项数据进行${shareType === '1' ? '公开共享' : '机构共享'}？`,
    () => toShare({ id: row.id, shareType }),
    '共享成功!'
  );
};
const postCopy = row => {
  postAction('确定将该项数据进行复制?', () => copy({ id: row.id }), '操作成功!');
};
const postAction = (message, actionFn, successMessage) => {
  ElMessageBox.confirm(message, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(actionFn)
    .then(() => {
      TabRefreshChange();
      ElMessage({ type: 'success', message: successMessage });
    });
};

onMounted(() => {
  options.value.menuWidth = 200;
  selectTab.value = 1;
  TabRefreshChange();
});

const rowSave = (row, done, loading) => {
  add(row).then(
    res => {
      TabRefreshChange();
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      visitplanitemRef.value.open(res.data.data,true);
      done();
    },
    error => {
      loading();
      window.console.log(error);
    }
  );
};
const rowUpdate = (row, index, done, loading) => {
  update(row).then(
    () => {
      // onLoad(page.value);
      TabRefreshChange();
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      done();
    },
    error => {
      loading();
      console.log(error);
    }
  );
};
const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};
const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      // onLoad(page.value);
      TabRefreshChange();
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      crud.value.toggleSelection();
    });
};
const handleExport = () => {
  let downloadUrl = `/blade-followupvisitplan/followUpVisitPlan/export-followUpVisitPlan?${
    website.tokenHeader
  }=${getToken()}`;
  const { name, lbType } = query.value;
  let values = {
    name_: name,
    lbType_: lbType,
  };
  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `CRF管理${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};
const searchReset = () => {
  query.value = {};
  TabRefreshChange();
  // onLoad(page.value, query.value);
};
const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  TabRefreshChange();
  // onLoad(page.value, params);
  done();
};
const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};
const selectionChange = list => {
  selectionList.value = list;
};
const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
  TabRefreshChange();
};
const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
  TabRefreshChange();
};
const refreshChange = () => {
  onLoad(page.value, query.value);
};
const TabRefreshChange = () => {
  query.value.shareType = null;
  if (selectTab.value === 1) {
    query.value.publicShare = '1';
  } else if (selectTab.value === 2) {
    query.value.deptShare = '1';
  }
  if (selectTab.value === 3) {
    query.value.create_user = userInfo.value.user_id;
  }
  onLoad(page.value, query.value);
};
const onLoad = (page, params = {}) => {
  loading.value = true;

  const { name, lbType } = query.value;

  let values = {
    name_: name,
    lbType_: lbType,
    descs: 'create_time',
    shareType: params.shareType || 1,
    ...params,
  };

  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    data.value.forEach(item => {
      item.isShareSelect = 3;
      if (item.publicShare == '1') {
        item.isShareBtn = '0';
        item.isShareSelect = 1;
      } else if (item.deptShare == '1') {
        item.isShareBtn = '6';
        item.isShareSelect = 2;
      }
    });
    loading.value = false;
    selectionClear();
  });
};
</script>

<style>
</style>
